import pandas as pd
from pdfplumber import open
from pandas import DataFrame,concat
from os import listdir
from os.path import join
from re import compile
from datetime import datetime

# with pdfplumber.open(r'C:\Users\95178\Desktop\发电小时数测算\pvsyst广东广西湖南湖北报告\广西pvsyst报告\106.62158260728236,23.328994351285857.pdf') as pdf:
#     for page in pdf.pages:
#         data = page.extract_text()
#         print(data)


def Fetch_data(filepath, filename):
    LAT = compile('项目设置\n(.+) 纬度 (\S+)°N')
    LON = compile('经度 (\S+)°E')
    Alt = compile('海拔 (-?\S+\s?)m')

    #单坡
    angle1 = compile('倾角/方位角 (\S+) / (\S+) ° 散射')
    angle2 = compile('使用的模型\n(\S+) 未定义三维场景')
    # 双坡的倾角、方位角
    double_angle = compile('倾角/方位角 (\S+) / (\S+) °\n(\S+) / (\S+)')


    #发电小时数
    year_irradiance_hours = compile('年单位发电量 (\S+\s?)kWh/kWp/年')

    January = compile('1月 (\S+) (\S+) (\S+) (\S+) (\S+) (\S+) (\S+) (\S+)')
    February = compile('2月 (\S+) (\S+) (\S+) (\S+) (\S+) (\S+) (\S+) (\S+)')
    March = compile('3月 (\S+) (\S+) (\S+) (\S+) (\S+) (\S+) (\S+) (\S+)')
    April = compile('4月 (\S+) (\S+) (\S+) (\S+) (\S+) (\S+) (\S+) (\S+)')
    May = compile('5月 (\S+) (\S+) (\S+) (\S+) (\S+) (\S+) (\S+) (\S+)')
    June = compile('6月 (\S+) (\S+) (\S+) (\S+) (\S+) (\S+) (\S+) (\S+)')
    July = compile('7月 (\S+) (\S+) (\S+) (\S+) (\S+) (\S+) (\S+) (\S+)')
    August = compile('8月 (\S+) (\S+) (\S+) (\S+) (\S+) (\S+) (\S+) (\S+)')
    September = compile('9月 (\S+) (\S+) (\S+) (\S+) (\S+) (\S+) (\S+) (\S+)')
    October = compile('10月 (\S+) (\S+) (\S+) (\S+) (\S+) (\S+) (\S+) (\S+)')
    November = compile('11月 (\S+) (\S+) (\S+) (\S+) (\S+) (\S+) (\S+) (\S+)')
    December = compile('12月 (\S+) (\S+) (\S+) (\S+) (\S+) (\S+) (\S+) (\S+)')

    Year = compile('年 (\S+) (\S+) (\S+) (\S+) (\S+) (\S+) (\S+) (\S+)')

    file = join(filepath, filename)
    with open(file) as pdf:
        result = {}
        data = ''
        for page in pdf.pages:
            data_one_page = page.extract_text()
            data += data_one_page + '\n'

        Lat = LAT.search(data)
        Lon = LON.search(data)
        ALT = Alt.search(data)
        # 单坡 包含水平情况
        ANGLE1 = angle1.search(data)
        ANGLE2 = angle2.search(data)
        # 双坡
        angle = double_angle.search(data)

        Jan = January.search(data)
        Feb = February.search(data)
        Mar = March.search(data)
        Apr = April.search(data)
        Ma = May.search(data)
        Jun = June.search(data)
        Jul = July.search(data)
        Aug = August.search(data)
        Sep = September.search(data)
        Oct = October.search(data)
        Nov = November.search(data)
        Dec = December.search(data)

        Hours = year_irradiance_hours.search(data)
        YEAR = Year.search(data)

        if Lat != None and Lon != None:
            result['site'] = Lat.group(1)
            result['lat'] = Lat.group(2)
            result['lon'] = Lon.group(1)
            result['altitude'] = ALT.group(1)

        if angle != None:
            result['Tilt1'] = angle.group(1)
            result['Azimuth1'] = angle.group(2)
            result['Tilt2'] = angle.group(3)
            result['Azimuth2'] = angle.group(4)
        elif ANGLE1 != None:
            result['Tilt1']=ANGLE1.group(1)
            result['Azimuth1']=ANGLE1.group(2)
            result['Tilt2'] = ''
            result['Azimuth2'] = ''
        elif ANGLE2 != None:
            result['Tilt1']=ANGLE2.group(1)
            result['Azimuth1']=ANGLE2.group(1)
            result['Tilt2'] = ''
            result['Azimuth2'] = ''

        if Hours != None:
            result['year_irradiance_hours'] = Hours.group(1)

        if YEAR != None:
            result['year_GHI'] = YEAR.group(1)
            result['year_DHI'] = YEAR.group(2)

            result['year_GlobInc'] = YEAR.group(4)
            result['year_GlobEff'] = YEAR.group(5)

            result['year_PR'] = YEAR.group(8)

        if Jan != None:
            result['Month1_GHI'] = Jan.group(1)
            result['Month2_GHI'] = Feb.group(1)
            result['Month3_GHI'] = Mar.group(1)
            result['Month4_GHI'] = Apr.group(1)
            result['Month5_GHI'] = Ma.group(1)
            result['Month6_GHI'] = Jun.group(1)
            result['Month7_GHI'] = Jul.group(1)
            result['Month8_GHI'] = Aug.group(1)
            result['Month9_GHI'] = Sep.group(1)
            result['Month10_GHI'] = Oct.group(1)
            result['Month11_GHI'] = Nov.group(1)
            result['Month12_GHI'] = Dec.group(1)
            #
            result['Month1_DHI'] = Jan.group(2)
            result['Month2_DHI'] = Feb.group(2)
            result['Month3_DHI'] = Mar.group(2)
            result['Month4_DHI'] = Apr.group(2)
            result['Month5_DHI'] = Ma.group(2)
            result['Month6_DHI'] = Jun.group(2)
            result['Month7_DHI'] = Jul.group(2)
            result['Month8_DHI'] = Aug.group(2)
            result['Month9_DHI'] = Sep.group(2)
            result['Month10_DHI'] = Oct.group(2)
            result['Month11_DHI'] = Nov.group(2)
            result['Month12_DHI'] = Dec.group(2)
            #
            result['Month1_GlobInc'] = Jan.group(4)
            result['Month2_GlobInc'] = Feb.group(4)
            result['Month3_GlobInc'] = Mar.group(4)
            result['Month4_GlobInc'] = Apr.group(4)
            result['Month5_GlobInc'] = Ma.group(4)
            result['Month6_GlobInc'] = Jun.group(4)
            result['Month7_GlobInc'] = Jul.group(4)
            result['Month8_GlobInc'] = Aug.group(4)
            result['Month9_GlobInc'] = Sep.group(4)
            result['Month10_GlobInc'] = Oct.group(4)
            result['Month11_GlobInc'] = Nov.group(4)
            result['Month12_GlobInc'] = Dec.group(4)

    datas = {filename[:-4]: result}
    datas = DataFrame(datas)
    return datas.T

if __name__ == '__main__':

    filepath = str(input('请输入文件路径:'))
    localPath = str(input('请输入保存文件存储路径:'))
    address_filename = str(input('请将省市地址文件放在同目录下,输入文件名称:'))
    local_filename = str(input('请输入保存文件名称:'))

    address = pd.read_excel(address_filename + '.xlsx', engine='openpyxl')

    allsite_data = DataFrame()
    for filename in listdir(filepath):
        print(filename)
        # 如果混合了不同的房型，需要分开跑：
        info = filename[:-4].split(',')
        tilt = int(info[-2])
        if tilt!=0:
            continue
        data_of_onesite = Fetch_data(filepath,filename)

        allsite_data = concat([allsite_data,data_of_onesite])

    print(allsite_data)
    #allsite_data.reset_index(inplace=True)
    allsite_data=allsite_data[['lon','lat','site','Tilt1','Azimuth1','Tilt2','Azimuth2', 'altitude',
    'Month1_GHI','Month1_DHI', 'Month1_GlobInc',
     'Month2_GHI', 'Month2_DHI', 'Month2_GlobInc',
     'Month3_GHI', 'Month3_DHI', 'Month3_GlobInc',
    'Month4_GHI', 'Month4_DHI', 'Month4_GlobInc',
    'Month5_GHI', 'Month5_DHI','Month5_GlobInc',
    'Month6_GHI', 'Month6_DHI', 'Month6_GlobInc',
     'Month7_GHI', 'Month7_DHI', 'Month7_GlobInc',
    'Month8_GHI','Month8_DHI', 'Month8_GlobInc',
    'Month9_GHI', 'Month9_DHI','Month9_GlobInc',
    'Month10_GHI', 'Month10_DHI', 'Month10_GlobInc',
     'Month11_GHI', 'Month11_DHI', 'Month11_GlobInc',
    'Month12_GHI','Month12_DHI', 'Month12_GlobInc',
     'year_GHI', 'year_DHI','year_GlobInc', 'year_GlobEff',
    'year_PR','year_irradiance_hours']]

    allsite_data.reset_index(inplace=True)
    allsite_data.rename(columns={'index':'文件名称'},inplace=True)
    allsite_data['合并地址'] = allsite_data['文件名称'].apply(lambda x : x.split(',')[0]+','+x.split(',')[1])
    print(allsite_data)
    address_data = pd.merge(address, allsite_data, left_on='百度地图经纬度', right_on='合并地址', how='outer')
    local_filepath = (localPath + '\\' + local_filename +'-Pvsyst仿真报告-'+str(datetime.now().strftime('%Y-%m-%d %H-%M-%S'))+'.xlsx')
    address_data.to_excel(local_filepath)
